<?php


namespace app\admin\controller;


use app\admin\service\RbacService;
use app\common\controller\CommonController;
use app\common\exception\ParameterFailedException;
use app\common\model\ArticleModel;
use app\common\model\MediaModel;
use app\common\service\Lang;
use app\common\validate\ArticleValidate;
use app\common\validate\RCBCValidate;
use think\facade\Db;
use think\Request;

class ArticleController extends CommonController
{
    public function getArticleList(Request $request)
    {
        $searchParams = self::getParam([]);
        $where        = [];
        foreach ($searchParams as $key => $value) {
            if (is_array($value) && $key === 'create_time') {
                $where[] = [
                    $key,
                    'between',
                    $value,
                ];
                continue;
            }
            if (strpos($value, '%') !== false) {
                $where[] = [
                    $key,
                    'like',
                    $value,
                ];
            }
            else {
                $where[] = [
                    $key,
                    '=',
                    $value,
                ];
            }
        }
        $articleListModel = (new ArticleModel())->getArticleList($where, '*', []);
        return retJson(Lang::GETDone, $articleListModel->toArray());
    }

    public function postArticle(Request $request)
    {
        $params = self::getParam(
            [
                'article_title',
                'article_content',
            ]
        );
        (new ArticleValidate())->goCheck(__FUNCTION__, $params);

        $articleModel          = new ArticleModel();
        $articleModel->title   = $params['article_title'];
        $articleModel->content = $params['article_content'];
        $articleModel->user_id = $request->userModel->getData('id');
        $articleModel->save();

        return retJson(Lang::POSTDone);

    }

    public function putArticle()
    {
        $params = self::getParam(
            [
                'article_id',
                'article_title',
                'article_content',
            ]
        );
        (new ArticleValidate())->goCheck(__FUNCTION__, $params);
        Db::startTrans();
        try {
            $articleModel = (new ArticleModel())->where('id', $params['article_id'])->find();
            if (!$articleModel) {
                throw new ParameterFailedException(['msg' => '数据不存在']);
            }
            $articleModel->title   = $params['article_title'];
            $articleModel->content = $params['article_content'];
            $articleModel->save();

            Db::commit();
            return retJson(Lang::PUTDone);
        } catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }
    }

    public function deleteArticle()
    {
        return retJson(Lang::DELETEDone);
    }
}
